package com.atguigu.gmall.product.init;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.product.entity.SkuInfo;
import com.atguigu.gmall.product.service.SkuInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Description 使用CommandLineRunner接口实现类，使得product服务一启动就向redis中写入bitmap中
 * SETBIT key offset value
 * @Return
 * @Author https://weiranyi.github.io
 * @Date Created in 2022-12-06 17:59
 **/
@Slf4j
@Component
public class InitCacheRunner implements CommandLineRunner {
    // 使用redis用到的类
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    // 获取商品详情数据用到的类
    @Autowired
    private SkuInfoService skuInfoService;

    // 初始化位图
    public void initBitMap() {
        List<SkuInfo> getIdsBySkuInfo = skuInfoService.lambdaQuery().select(SkuInfo::getId).eq(SkuInfo::getIsSale,1).list();
        getIdsBySkuInfo.stream().forEach((item) -> {
            stringRedisTemplate.opsForValue().setBit(RedisConst.BITMAP_SKU_NAME, item.getId(), true);
            log.info("bitmap位图-skuInfo-id初始化完成");
        });
    }

    @Override
    public void run(String... args) throws Exception {
        this.initBitMap();
        log.info("InitRunner...启动run方法");
    }
}
